#!/bin/sh

## By demure (demuredemeanor)
## Version 0.4

## This script is intended to make it easy to see which passwords need updating due to age with the password manager `pass`.
## Usage: This script will display .gpg files with modification dates older than 300 days by default.
## NOTE: Editing the pass entry without changing the password itself will also change the file's modification date

if [ $# -gt 1 ]; then
    echo "Too many inputs. Only expecting integer of how many days old to display."
    exit
fi

if [ $# -eq 1 ]; then
    if [ "$1" -ge 0 ] 2>/dev/null; then
        DAYS="$1"
      else
        echo "Bad input. Expecting integer of how many days old to display."
    fi
fi

if [ $# -eq 0 ]; then
    DAYS=300
fi


## Test if pass default dir overridden
if [ -z ${PASSWORD_STORE_DIR} ]; then
    DIR="$HOME/.password-store"
  else
    DIR="${PASSWORD_STORE_DIR}"
fi


## Before we check modification times, we need to ensure that the local password store's file modification dates match git
## Citation: https://stackoverflow.com/a/55609950/2327476
cd ${DIR}
git ls-tree -r --name-only HEAD | while read filename; do 
  unixtime=$(git log -1 --format="%at" -- "${filename}")
  touchtime=$(date -d @$unixtime +'%Y%m%d%H%M.%S')
  touch -t ${touchtime} "${filename}"
done


## Match .gpg files other that X days, sort by date, cut off the extra bits before the parent dir, output in cols and display in less
find "${DIR}" -name '*.gpg' -mtime +300 -printf '%TY-%Tm-%Td %TH:%TM %h %f\n' | sort -n | sed 's/\/.*\///' | column -t | less
